<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <CommunityTree @node-click="handleCommunityNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="" prop="keyWord">
            <el-input placeholder="请输入内容" v-model.trim="keyWord">
              <template #prepend>
                <el-select v-model="kType" placeholder="请选择" class="!w-120px">
                  <el-option label="集中器地址" value="serialServerName" />
                  <el-option label="集中器编码" value="serialServerNo" />
                  <el-option label="安装人员" value="installMemberName" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="厂家" prop="factoryCode">
            <el-select
              v-model="queryParams.factoryCode"
              placeholder="厂家"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in meterFactoryDictDatas"
                :key="parseInt(dict.value)"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="在线状态" prop="onlineStatus">
            <el-select
              v-model="queryParams.onlineStatus"
              placeholder="通电状态"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in onLineStateDictDatas"
                :key="parseInt(dict.value)"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              plain
              @click="openForm('create', undefined, queryParams.commId)"
              v-hasPermi="['zwsj:meter-serial-server:create']"
            >
              <Icon icon="ep:plus" /> 新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="updateOnLineStatus"
              v-hasPermi="['zwsj:meter-serial-server:update']"
              ><Icon icon="ep:refresh" />更新在线时间</el-button
            >
            <el-button
              type="success"
              plain
              @click="updateRelaMeters"
              v-hasPermi="['zwsj:meter-serial-server:update']"
              ><Icon icon="ep:refresh" />刷新集中器电表</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="ID" align="center" prop="id" width="60"/>
          <el-table-column label="社区" align="center" prop="community.name" width="100" />
          <el-table-column
            label="集中器地址/编码"
            align="left"
            prop="serialServerName"
            min-width="230"
            show-overflow-tooltip="true"
          >
            <template #default="scope">
              <div>地址：<el-link type="primary" @click="getMeters(scope.row.id)">{{
                scope.row.serialServerName
              }}</el-link></div>
              <div>编码：{{ scope.row.serialServerNo }} <dict-tag :type="DICT_TYPE.METER_FACTORY" :value="scope.row.factoryCode" /></div>
            </template>
          </el-table-column>
          <el-table-column
            label="安装人员/最近在线时间"
            align="left"
            prop="lastOnlineTime"
            width="230">
            <template #default="scope">
              <div>安装人员：{{ scope.row.installMemberName }}</div>
              <div>在线时间：{{ formatDate(scope.row.lastOnlineTime,'YYYY-MM-DD HH:mm') }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="left" prop="onlineStatus" width="160">
            <template #default="scope">
              <div>在线状态：<dict-tag :type="DICT_TYPE.ONLINE_STATE" :value="scope.row.onlineStatus" /></div>
              <div>使用状态：<dict-tag :type="DICT_TYPE.METER_SERIAL_SERVER_USE_STATUS" :value="scope.row.useStatus" /></div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="外系统关联ID" align="center" prop="externalLinkId" width="120" /> -->
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['zwsj:meter-serial-server:update']"
              >
                修改
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['zwsj:meter-serial-server:delete']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改对话框 -->
  <MeterSerialServerForm ref="formRef" @success="getList" />
  <MeterSerialServerMeters ref="meterSerialServerMetersRef" />
</template>
<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as MeterSerialServerApi from '@/api/zwsj/meterSerialServer'
import MeterSerialServerForm from './MeterSerialServerForm.vue'
import MeterSerialServerMeters from './MeterSerialServerMeters.vue'
import CommunityTree from '@/views/zwsj/common/CommunityTree.vue'
import { ElNotification } from 'element-plus'

defineOptions({ name: 'MeterSerialServer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const onLineStateDictDatas = getIntDictOptions(DICT_TYPE.ONLINE_STATE)
const meterFactoryDictDatas = getIntDictOptions(DICT_TYPE.METER_FACTORY)
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const multipleSelection = ref([])

const keyWord = ref('')
const kType = ref('serialServerName')
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  parentId: 0,
  commId: null,
  onlineStatus: null,
  serialServerName: '',
  serialServerNo: '',
  installMemberName: '',
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
      queryParams.serialServerName = ''
      queryParams.serialServerNo = ''
      queryParams.installMemberName= ''
    if (kType.value == 'serialServerName') {
      queryParams.serialServerName = keyWord.value
    } else if (kType.value == 'serialServerNo') {
      queryParams.serialServerNo = keyWord.value
    }else if (kType.value == 'installMemberName') {
      queryParams.installMemberName = keyWord.value
    }

    const data = await MeterSerialServerApi.getMeterSerialServerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  keyWord.value = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理社区被点击 */
const handleCommunityNodeClick = async (row) => {
  queryParams.commId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, commId?: number) => {
  formRef.value.open(type, id, commId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MeterSerialServerApi.deleteMeterSerialServer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleSelectionChange = async (val: any) => {
  multipleSelection.value = val
}

const updateOnLineStatus = async () => {
  ElMessageBox.confirm('该操作将会同步集中器在线状态及当前在线的时间，确定继续?', 'info', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  })
    .then(() => {
      MeterSerialServerApi.updateMeterSerialServerOnLineStatus().then((data) => {
        if (data) {
          ElNotification({
            type: 'success',
            title: `成功`,
            message: '更新在线状态成功'
          })
          getList()
        } else {
          ElNotification({
            type: 'error',
            title: `失败`,
            message: '更新在线状态失败'
          })
          getList()
        }
      })
    })
    .catch(() => {
      //ElMessage({ type: 'info', message: 'Delete canceled' })
    })
}

const updateRelaMeters = async () => {
  if (multipleSelection.value.length == 0) {
    ElNotification({
      title: `错误`,
      message: '请选择要刷新的数据'
    })
    return false
  }

  let ids: number[] = []
  multipleSelection.value.forEach((it, idx) => {
    ids.push(it.id)
  })

  ElMessageBox.confirm(
    '该操作将会刷新集中器对应的电表数据（通常在安装电表后进行），确定继续?',
    'info',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  )
    .then(() => {
      MeterSerialServerApi.callMeterSerialServerAutoReport(ids).then((data) => {
        if (data) {
          ElNotification({
            type: 'success',
            title: `成功`,
            message: '刷新成功'
          })
          getList()
        } else {
          ElNotification({
            type: 'error',
            title: `失败`,
            message: '刷新失败'
          })
        }
      })
    })
    .catch(() => {
      //ElMessage({ type: 'info', message: 'Delete canceled' })
    })
  //
}

const meterSerialServerMetersRef = ref()
const getMeters = async (serverId: number) => {
  let autoReportMeterNos = await MeterSerialServerApi.getMeterSerialServerAutoReportMeters(serverId)
  meterSerialServerMetersRef.value.open(serverId, autoReportMeterNos)
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>
